<?php

class Userchat_model extends Base_Model
{
    Const TABLE = 'user_v2_chat';

    public function __construct()
    {
        parent::__construct();
        $this->load->database();
    }

    /**
     * 聊天列表
     *
     * @param $where
     * @param $offset
     * @param $limit
     * @return mixed
     */
    public function getChatList($where, $offset, $limit)
    {
        $data = $this->db->select('uc.*, u.userIcon as userIcon1, uv.userIcon as userIcon2')->from(self::TABLE. ' as uc')
                    ->join('user_v2 as uv', 'uv.uid = uc.guiderId')
                    ->join('user_v2 as u', 'u.uid = uc.uid', 'LEFT')
                    ->where($where)
                    ->limit($limit, $offset)
                    ->get()
                    ->result_array();
        if($data){
            foreach($data as &$v){
                if($v['fromUser']){
                    $v['userIcon'] = $v['userIcon1'];
                }else{
                    $v['userIcon'] = $v['userIcon2'];
                }
                unset($v['userIcon1']);
                unset($v['userIcon2']);
            }
        }

        return $data;
    }

    /**
     * 添加聊天消息
     * @param $data
     * @return int
     */
    public function addChat($data)
    {
        $this->db->insert(self::TABLE, $data);
        return $this->db->insert_id();
    }

    /**
     * 私信列表
     *
     * @param $uid
     * @param $type
     * @return mixed
     */
    public function getChatByUser($uid, $type)
    {
        if($type == 'GUIDER'){
            $sql = "
SELECT
	uc.message,uc.created,uv.userIcon
FROM
	user_v2_chat uc
LEFT JOIN user_v2 uv ON uc.uid = uv.uid
WHERE
	uc.guiderId = ".$uid."
AND uc.fromUser = 1
GROUP BY
	uc.uid
ORDER BY uc.created
";
        }else{
            $sql = "
SELECT
	uc.message,uc.created,uv.userIcon
FROM
	user_v2_chat uc
LEFT JOIN user_v2 uv ON uc.guiderId = uv.uid
WHERE
	uc.uid = ".$uid."
AND uc.fromUser = 0
GROUP BY
	uc.guiderId
ORDER BY uc.created;
";
        }
        $query = $this->db->query($sql);
        return $query->result_array();
    }

}